package org.example.booksmanagementsystem.service;

import lombok.extern.slf4j.Slf4j;
import org.example.booksmanagementsystem.enums.BookInfoStatusEnum;
import org.example.booksmanagementsystem.model.BookInfo;
import org.example.booksmanagementsystem.model.PageRequest;
import org.example.booksmanagementsystem.model.PageResult;
import org.example.booksmanagementsystem.redissync.IdStatic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Slf4j
@Service
public class SpecialDealAdminService {
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;


    public PageResult<BookInfo> getSpecialBookListByPage(PageRequest pageRequest) {
        if(pageRequest==null){
            return null;
        }

        //获取表中数据的总数
        Integer count = getAllBookInfoFromRedis().size();

        //获取该页的数据
        List<BookInfo> bookInfoList = getRequestPage(pageRequest);


        //根据status 修改 statusCN
        for(BookInfo it : bookInfoList){
            // 使用枚举类设置图书的状态
            it.setStatusCN(BookInfoStatusEnum.getNameByCode(it.getStatus()).getName());
        }

        // 创建PageResult对象返回给Controller
        return new PageResult<BookInfo>(count,bookInfoList,pageRequest);

    }

    // 根据RequestPage获取数据
    public List<BookInfo> getRequestPage(PageRequest pageRequest){

        // 获取redis数据的总数
        List<BookInfo> bookInfoList = getAllBookInfoFromRedis();

        // 总的数据的个数
        Integer size = bookInfoList.size() - 1;

        if(pageRequest.getOffset()+9 >size){
            bookInfoList.subList(pageRequest.getOffset(),size);
            return bookInfoList;
        }

        bookInfoList.subList(pageRequest.getOffset(),pageRequest.getOffset()+9);

        return bookInfoList;
    }

    // 从Redis中取出所有bookInfo
    public List<BookInfo> getAllBookInfoFromRedis() {
        List<BookInfo> resultList = new ArrayList<>();

        //从Redis中取出所有bookInfoId:前缀的数据

        // 1：获取所有以"bookInfoId:"开头的键
        String keyPattern = "bookInfoId:*";
        Set<String> keys = redisTemplate.keys(keyPattern);


        // 2：遍历键，逐个获取对应的值
        for (String key : keys) {
            BookInfo value = (BookInfo)redisTemplate.opsForValue().get(key);
            log.info("----------value-----"+value);
            // 放入list中
            resultList.add(value);
        }

        return resultList;
    }

    // 添加图书
    public boolean addBookInfo(BookInfo bookInfo) {

        //找出最大的Id
        Integer maxId = 0;

        // 1：获取所有以"bookInfoId:"开头的键
        String keyPattern = "bookInfoId:*";
        Set<String> keys = redisTemplate.keys(keyPattern);


        // 步骤2：遍历键，逐个获取对应的值
        for (String key : keys) {
            BookInfo value = (BookInfo)redisTemplate.opsForValue().get(key);
            if(value.getId()>maxId){
                maxId = value.getId();
            }

        }
        // 下个id从 maxId +1 开始
        IdStatic.setId(maxId +1);

        try {
            Integer id = IdStatic.getId();

            bookInfo.setId(id);
            bookInfo.setCreateTime();
            bookInfo.setUpdateTime();

            String idString = "bookInfoId:" + id;
            redisTemplate.opsForValue().set(idString, bookInfo);
            return true;
        }catch (Exception e){
            log.error("redis-添加图书失败");
            return false;
        }
    }

    //根据ID查找图书
    public BookInfo getBookInfoById(Integer id){

        BookInfo bookInfo = null;

        // 1：获取所有以"bookInfoId:"开头的键
        String keyPattern = "bookInfoId:*";
        Set<String> keys = redisTemplate.keys(keyPattern);
//        log.info("------keys:"+keys);

        // 2：遍历键，逐个获取对应的值
        for (String key : keys) {
            BookInfo value = (BookInfo)redisTemplate.opsForValue().get(key);
//            log.info("--------service---value:"+value);
            if(id.equals(value.getId())){
                bookInfo = value;
//                log.info("--------service---bookInfo:"+bookInfo);
                return bookInfo;
            }
        }

        return bookInfo;
    }

    // 更新图书信息
    public boolean updateSpecialBook(BookInfo bookInfo) {
        // 获取所有以"bookInfoId:"开头的键
        String keyPattern = "bookInfoId:*";
        Set<String> keys = redisTemplate.keys(keyPattern);

        for (String key : keys) {
            BookInfo value = (BookInfo)redisTemplate.opsForValue().get(key);
//            log.info("--------service---value:"+value);

            //找相同的ID
            if(bookInfo.getId().equals(value.getId())){
                bookInfo.setUpdateTime();
                //替换bookInfo
                redisTemplate.opsForValue().set(key,bookInfo);
                log.info("--------service---bookInfo:"+bookInfo);
                return true;
            }
        }

        return false;
    }

    public boolean updateBookInfo(BookInfo bookInfo){
        // 获取所有以"bookInfoId:"开头的键
        String keyPattern = "bookInfoId:*";
        Set<String> keys = redisTemplate.keys(keyPattern);

        for (String key : keys) {
            BookInfo value = (BookInfo)redisTemplate.opsForValue().get(key);
//            log.info("--------service---value:"+value);

            //找相同的ID
            if(bookInfo.getId().equals(value.getId())){
                value.setUpdateTime();
                value.setStatus(bookInfo.getStatus());
                redisTemplate.opsForValue().set(key,value);
                log.info("--------service---bookInfo:"+bookInfo);
                return true;
            }
        }

        return false;
    }
}
